package com.wosai.teach.handler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.android.agnetty.core.event.ExceptionEvent;
import com.android.agnetty.core.event.MessageEvent;
import com.android.agnetty.future.http.HttpHandler;
import com.android.agnetty.utils.LogUtil;
import com.wosai.teach.pojo.HomeWork;
import com.wosai.teach.pojo.JsonResult;

public class HomeWorkHandler extends HttpHandler {

	public HomeWorkHandler(Context context) {
		super(context);
	}

	@Override
	public boolean onEncode(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onCompress(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onDecompress(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onDecode(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public void onHandle(MessageEvent evt) throws Exception {
		String response = new String((byte[]) evt.getData(), "utf-8");
		LogUtil.d(HomeWorkHandler.class.getCanonicalName() + response);
		if (!TextUtils.isEmpty(response)) {
			System.out.println(response);
			JsonResult jr = JSON.parseObject(response, JsonResult.class);
			List<HomeWork> hwList = null;
			if (jr.getResult() == 0) {
				JSONArray jsonArray = JSON
						.parseArray(jr.getObject().toString());
				if (jsonArray != null) {
					hwList = new ArrayList<HomeWork>();
					Iterator<Object> it = jsonArray.iterator();
					while (it.hasNext()) {
						JSON json = (JSON) it.next();
						HomeWork hw = JSON.parseObject(json.toString(),
								HomeWork.class);
						hwList.add(hw);
					}
				}
				evt.getFuture().commitComplete(hwList);
			} else {
				evt.getFuture().commitComplete(hwList);
			}
		}
	}

	@Override
	public void onException(ExceptionEvent evt) {
		evt.getException().printStackTrace();
	}

	@Override
	public void onDispose() {

	}

}
